
package cz.muni.fi.pa165.rentalofconstructionmachinery.restclient;

import cz.muni.fi.pa165.rentalofconstructionmachinery.CustomerType;
import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.CustomerDTO;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author Zuzana Krejcova
 */
public class CustomerRestController {
    
    private static String CUSTOMER_URL = App.WEBAPP_LOCATION+"customer/";
    private static RestTemplate rt = new RestTemplate();
    private static HttpHeaders httpHeaders;
    
    public static void setHttpHeaders(HttpHeaders headers) {
        httpHeaders = headers;
    }
    
    public static void deleteCustomer(Long id) throws URISyntaxException {
        String url = CUSTOMER_URL+id;
        rt.exchange(new URI(url), HttpMethod.DELETE, new HttpEntity<>(httpHeaders), Object.class);
    }
    
    public static void newCustomer(String name, CustomerType type, String username, String password) {
        CustomerDTO customer = new CustomerDTO(null, name, type, username, password, 5);
        rt.postForLocation(CUSTOMER_URL, new HttpEntity<>(customer, httpHeaders));
    }
    
    public static void editCustomer(Long id, String name, CustomerType type, String username, String password) {
        CustomerDTO customer = new CustomerDTO(id, name, type, username, password, 5);
        String url = CUSTOMER_URL+id;
        rt.put(url, new HttpEntity<>(customer, httpHeaders));
    }
    
    public static CustomerDTO customerDetails(Long id) throws URISyntaxException {
        String url = CUSTOMER_URL+id;
        HttpEntity re = rt.exchange(new URI(url), HttpMethod.GET, new HttpEntity<>(httpHeaders), CustomerDTO.class);
        return (CustomerDTO)re.getBody();
    }
    
    public static List<CustomerDTO> listCustomers() throws URISyntaxException {
        HttpEntity re = rt.exchange(new URI(CUSTOMER_URL), HttpMethod.GET, new HttpEntity<>(httpHeaders), CustomerDTO[].class);
        return Arrays.asList((CustomerDTO[])re.getBody());
    }
}
